package com.example.calculationtest

import android.app.Application
import android.content.Context
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.SavedStateHandle
import kotlin.random.Random

const val KEY_HIGH_SCORE = "key_high_score"
const val KEY_LEFT_NUMBER = "key_left_number"
const val KEY_RIGHT_NUMBER = "key_right_number"
const val KEY_OPERATOR = "key_operator"
const val KEY_ANSWER = "key_answer"
const val KEY_CURRENT_SCORE = "key_current_score"
const val KEY_WIN_FLAG = "key_win_flag"
const val KEY_LEVEL = "key_level"
const val KEY_LEVEL_STATUS = "key_level_status"
const val SAVE_SHP_DATA_NAME = "save_shp_data_name"

class MyViewModel(application: Application, handle: SavedStateHandle) :
    AndroidViewModel(application) {


    private val map = mapOf(
        20 to "简单模式",
        40 to "中等模式",
        50 to "困难模式"
    )
    private val shp = application.getSharedPreferences(SAVE_SHP_DATA_NAME, Context.MODE_PRIVATE)
    val level = handle.getLiveData(KEY_LEVEL, 20)
    val highScore = handle.getLiveData(KEY_HIGH_SCORE, shp.getInt(KEY_HIGH_SCORE, 0))
    val operator = handle.getLiveData(KEY_OPERATOR, "+")
    val leftNumber = handle.getLiveData(KEY_LEFT_NUMBER, 0)
    val rightNumber = handle.getLiveData(KEY_RIGHT_NUMBER, 0)
    val answer = handle.getLiveData(KEY_ANSWER, 0)
    val currentScore = handle.getLiveData(KEY_CURRENT_SCORE, 0)
    val winFlag = handle.getLiveData(KEY_WIN_FLAG, false)

    fun generator(level: Int) {
        val x = Random.nextInt(level) + 1
        val y = Random.nextInt(level) + 1

        if (x % 2 == 0) {
            operator.value = "+"
            if (x > y) {
                answer.value = x
                leftNumber.value = y
                rightNumber.value = x - y
            } else {
                answer.value = y
                leftNumber.value = x
                rightNumber.value = y - x
            }
        } else {
            operator.value = "-"
            if (x > y) {
                answer.value = x - y
                leftNumber.value = x
                rightNumber.value = y
            } else {
                answer.value = y - x
                leftNumber.value = y
                rightNumber.value = x
            }
        }
    }

    fun answerCorrect() {
        currentScore.value = currentScore.value!! + 1
        if (currentScore.value!! > highScore.value!!) {
            highScore.value = currentScore.value
            winFlag.value = true
        }
        generator(20)
    }

    fun saveHighScore() {
        val edit = shp.edit()
        edit.putInt(KEY_HIGH_SCORE, highScore.value!!.toInt())
        edit.apply()
    }
}